<template>
  <tab-module-container :show-page-tools="true">
    <template #Slot-Conf-Module-Header>
      <p class="accounts-title font-20-bold">账号管理</p>
    </template>

    <template #Slot-Conf-Module-Tools-Left>
      <global-input-search
        v-model:value="tableAttr.searchObj.search"
        placeholder="手机号/姓名"
        @search="setTableData(true)"
      ></global-input-search>
    </template>

    <template #Slot-Conf-Module-Tools-Right>
      <a-button
        v-if="g6Permission.showBtn('add-account')"
        type="primary"
        @click="PageButtonClick('add-account')"
      >
        新增</a-button
      >
    </template>

    <template #Slot-Conf-Module-Content>
      <div class="_table">
        <global-table
          :data-source="tableAttr.data"
          :selected-row-keys="tableAttr.selectedKeys"
          :loading="tableAttr.loading"
          :columns="columns"
          :show-operation="true"
          :use-select="false"
          :operation-width="264"
        >
          <template #operation="{ record }">
            <div class="operations">
              <div
                :key="btn.code"
                v-for="btn in C_ShowTableBtn(record)"
                class="operation-item-btn"
              >
                <!-- <div>{{ btn.title }}</div> -->
                <div
                  v-if="!btn.children"
                  class="btn-text"
                  @click="PageButtonClick(btn.code, record)"
                >
                  {{ btn.title }}
                </div>
                <a-dropdown v-else v-model:open="record.dataAuthMenuDown">
                  <div class="ant-dropdown-link" @click.prevent>
                    {{ btn.title }}
                    <down-outlined
                      v-if="!record.dataAuthMenuDown"
                    ></down-outlined>
                    <up-outlined v-else></up-outlined>
                  </div>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item
                        :key="child.code"
                        v-for="child in btn.children"
                        class="menu-item"
                        @click="
                          dataAuthClick(child.code as DataAuthType, record)
                        "
                      >
                        {{ child.title }}
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </div>
            </div>
          </template>
        </global-table>

        <global-pagination
          :current="tableAttr.current"
          :page-size="tableAttr.pageSize"
          :total="tableAttr.total"
          @change="setTablePagination"
        ></global-pagination>
      </div>
    </template>
  </tab-module-container>

  <update-password
    v-if="C_MountSub('password')"
    v-model:type="modalType"
    :user-id="userId"
    @ok="setTableData(true)"
  ></update-password>

  <add-edit-account
    v-if="C_MountSub('addEdit')"
    v-model:type="modalType"
    :user-id="userId"
    @ok="setTableData(true)"
  ></add-edit-account>

  <role-transfer
    v-if="C_MountSub('transfer')"
    v-model:type="modalType"
    :user-id="userId"
    @ok="setTableData(true)"
  ></role-transfer>
  <!-- v-if="C_MountSub('cameraDataAuth')" -->
  <camera-data-permissions
    v-if="C_MountSub('cameraDataAuth')"
    v-model:save-data="saveData"
    v-model:type="modalType"
    :user-id="userId"
    @ok="setTableData(true)"
  ></camera-data-permissions>
  <alarm-data-permissions
    v-if="C_MountSub('alarmDataAuth')"
    v-model:save-data="saveData"
    v-model:type="modalType"
    :user-id="userId"
    @ok="setTableData(true)"
  >
  </alarm-data-permissions>
</template>

<script setup lang="ts">
import { g6UseTable } from "glasssix-vue3-hooks";
import { g6StorageValue, g6Permission } from "glasssix-utils-ts";
import { useDeleteModal } from "@/global-hooks/base.hooks";
import {
  UpdatePassword,
  RoleTransfer,
  AddEditAccount,
  TabModuleContainer,
  CameraDataPermissions,
  AlarmDataPermissions,
} from "../../../components/index";
import { DownOutlined } from "@ant-design/icons-vue";
import { AccountAPI } from "../../../api";
import type { TsAccountModalType, DataAuthType } from "../../../type";

const $message: any = inject("$message");
const { setOpenDeleteModal } = useDeleteModal();

const { tableAttr, setTableData, setTablePagination } = g6UseTable(
  AccountAPI.list
);

const logonUser = g6StorageValue.get("session", "userInfo");
const saveData = ref([]);

const columns: TsGlobalType.TsTableColumn[] = [
  {
    dataIndex: "userNumber",
    title: "手机号码(账号)",
    width: 180,
    ellipsis: true,
  },
  { dataIndex: "userName", title: "用户姓名", width: 180, ellipsis: true },
  { dataIndex: "roleName", title: "角色", width: 180, ellipsis: true },
  { dataIndex: "createName", title: "创建人", width: 180, ellipsis: true },
  { dataIndex: "createdTime", title: "创建时间", sorter: true, ellipsis: true },
];

// 弹窗状态类型
const modalType = ref<TsAccountModalType>();
const userId = ref("");

const PageButtonClick = async (
  btnCode: string,
  record?: Record<string, any>
): Promise<void> => {
  let newItem: Record<string, any> = record ? record : {};

  if (btnCode === "add-account" || btnCode === "edit-account") {
    userId.value = record ? newItem.id : "";
    modalType.value = "addEdit";
  }
  if (btnCode === "reset-password") {
    userId.value = record ? newItem.id : "";
    modalType.value = "password";
  }

  if (btnCode === "accounts-list-transfer") {
    userId.value = record ? newItem.id : "";
    modalType.value = "transfer";
  }

  if (btnCode === "single-delete") {
    const deleteModalInfo = {
      title: `请确认是否删除账号：“${newItem.userName}”？`,
      okText: "删除",
      cancelText: "取消",
    };
    const deleteFun = async (): Promise<void> => {
      let res: TsRes = await AccountAPI.delete([newItem.id]);
      if (res.code === 0) {
        tableAttr.data = tableAttr.data.filter(
          (row: Record<string, any>) => row.id !== newItem.id
        );
        tableAttr.total = tableAttr.total - 1;
        $message.success("删除成功");
        setTableData();
      }
    };
    setOpenDeleteModal(deleteFun, deleteModalInfo);
  }
};
const dataAuthClick = (code: DataAuthType, record?: Record<string, any>) => {
  userId.value = record ? record.id : "";
  if (code === "camera") {
    modalType.value = "cameraDataAuth";
    return;
  }
  if (code === "alarm") {
    modalType.value = "alarmDataAuth";
    return;
  }
};

const C_MountSub = computed(() => {
  return function (type: TsAccountModalType | "") {
    return modalType.value === type;
  };
});

const C_ShowTableBtn = computed(() => {
  return function (row: Record<string, any>) {
    // 非超管账号登录
    // 非超管账号显示: 编辑、删除、修改密码、数据权限
    // 超管账号显示: 空白
    //
    // 超管账号登录
    // 非超管账号显示: 编辑、删除、修改密码、数据权限
    // 超管账号自身显示: 编辑、转移、修改密码
    let btns = [];

    g6Permission.showBtn("edit-account") &&
      btns.push({ title: "编辑", code: "edit-account" });
    g6Permission.showBtn("reset-password") &&
      btns.push({ title: "修改密码", code: "reset-password" });
    row.roleId !== 1 &&
      g6Permission.showBtn("single-delete") &&
      btns.push({ title: "删除", code: "single-delete" });

    row.roleId !== 1 &&
      g6Permission.showBtn("data-auth") &&
      btns.push({
        title: "数据权限",
        code: "data-auth",
        children: [
          { title: "摄像头权限", code: "camera" },
          { title: "报警器权限", code: "alarm" },
        ],
      });
    const isSuperAccount = logonUser ? Number(logonUser.roleId) === 1 : false;

    if (isSuperAccount && row.roleId === 1) {
      g6Permission.showBtn("accounts-list-transfer") &&
        btns.push({ title: "转移", code: "accounts-list-transfer" });
    } else if (!isSuperAccount && row.roleId === 1) {
      btns = [];
      btns = [];
    }

    return btns;
  };
});

onMounted(() => {
  setTableData();
});
</script>

<style lang="less" scoped>
._table {
  display: flex;
  height: calc(100vh - 76px - 44px - 180px);
  padding: 20px 0 0;
  flex-direction: column;
  justify-content: space-between;
}

.accounts-title {
  color: rgba(240, 246, 252, 0.95);
}

:deep(.menu-item) {
  color: @text03 !important;

  &:hover {
    color: @text01 !important;
    background-color: #171e30 !important;
  }
}

.ant-dropdown-link {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  white-space: nowrap;
}

.operations {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;

  .operation-item-btn {
    min-width: 28px;
    height: 22px;
    color: @link01;

    .btn-text {
      white-space: nowrap;
    }

    &:hover {
      opacity: 0.85;
      cursor: pointer;
    }
  }
}
</style>
